package se.djupfeldt.oscar.logbook.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;

public class ConnectionHandler implements Runnable {
    private Socket clientSocket;
    public ConnectionHandler(Socket clientSocket) {
	this.clientSocket = clientSocket;
    }

    @SuppressWarnings("unused")
    @Override
    public void run() {
	try {
	    InputStream in = clientSocket.getInputStream();
	    OutputStream out = clientSocket.getOutputStream();
	    while (!clientSocket.isClosed()) {
		byte[] header = new byte[4];
		if (in.read(header) > 0 ) {
		    System.out.println(Arrays.toString(header));
		    handleMessage(header);
		}
		Thread.sleep(16);
	    }
	} catch (IOException e) {
	    e.printStackTrace();
	} catch (InterruptedException e) {
	    e.printStackTrace();
	} finally {
	    ServerHandler.getInstance().removeClient(this);
	}
    }
    
    private void handleMessage(byte[] header) throws IOException {
	if (header.length == 4) {
	    if (header[0] == 1 &&
		    header[1] == 1 &&
		    header[2] == 1 &&
		    header[3] == 1) {
		clientSocket.close();
	    }
	}
    }

    public Socket getClientSocket() {
	return clientSocket;
    }

}
